import slugify from "slugify";
import pinyin from "pinyin";

/**
 * 生成唯一 slug
 * @param {string} str - 原始字符串
 * @param {string[]} slugList - 已存在的 slug 列表
 * @param {object} options - slugify 选项
 * @returns {Promise<string>} 唯一 slug
 */
export default async function generateSlugify(str, slugList = [], options = {}) {
  if (!str || typeof str !== "string") return "";
  if (!Array.isArray(slugList)) slugList = [];

  const pyArray = pinyin(str, { style: pinyin.STYLE_NORMAL, heteronym: false });
  const pyStr = pyArray.map(item => item.join('')).join(' ');
  const pyStrLimited = pyStr.split(' ').slice(0, 4).join(' ');
  let baseSlug = slugify(pyStrLimited, { lower: true, strict: true, trim: true, ...options });
  let finalSlug = baseSlug;
  let counter = 1;

  // 只用传入的 slugList 判断唯一性
  while (slugList.includes(finalSlug)) {
    finalSlug = `${baseSlug}-${counter}`;
    counter++;
  }

  return finalSlug;
}